#!/usr/bin/perl
#
# Searches a specific folder for search criteria using Spotlight's
# indexes.  Woot!
#
#  Author: Jim Turner <myztikjenz@gmail.com>
# License: MIT OpenSource; do whatever you'd like to with this, no restrictions
#
# To use, create a web form that passes in two arguments:
# 1) 'path', the POSIX path to the folder you want to search in
#    (e.g., /Users/joe/Documents)
# 2) 'token', what you want to search for.
#
# This will look for a stylesheet named main.css located in the
# same folder it is located in.  No error if there isn't one found.
#
#################################################################
use CGI;

$mdfind = '/usr/bin/mdfind';

my $cgi = new CGI;

if( $cgi->param( 'submit' ) &&
	($cgi->param( 'token' ) ne "") )
{
	my $searchPath  = $cgi->param( 'path' );
	my $searchToken = $cgi->param( 'token' );

	my $rootPath = $searchPath;
	$rootPath    =~ s/^.+\/(.+)$/$1/;

	print $cgi->header();
	print $cgi->start_html( -title => "Search results for '$searchToken' in [$rootPath]",
							-style => { 'src' => 'main.css' } );
	
	my $cmd = sprintf( "%s \"%s\" -onlyin \"%s\"", $mdfind, $searchToken, $searchPath );
	
	my @results = `$cmd`;

	if( $#results < 0 )
	{
		print "No matches to \"$searchToken\" found\n";
	}
	else
	{
		foreach my $path ( @results )
		{
			chomp( $path );
			next if( $path =~ /~$/ );  #skip edit files
			
			my @pathComponents = split( '/', $path );

			my $filename = $pathComponents[$#pathComponents];
			my $URLPath  = $pathComponents[$#pathComponents-1];
			
			print "<a href = \"$URLPath/$filename\">$filename</a><br>\n";
		}
	}
	
	print "<hr width = \"300px;\" align = \"left\" noshade>\n";
	
	print $cgi->end_html();
}
else
{
	print $cgi->header();
	print $cgi->start_html( -title => "No search criteria provided!",
							-style => { 'src' => 'main.css' } );

	print << "ENDhtml";
No search criteria provided... muy triste!
<hr width = "300px;" align = "left" noshade>
ENDhtml

	print $cgi->end_html();

	exit();
}